import { 
  addAuth, 
  apiInterceptors, 
  getAuthPage, 
  updateAuth,
  get_connect_group,
  get_app_list,
  get_flow_list,
  get_knowledge_group
} from '@/client/api';
import { CreateAppParams } from '@/types/app';
import { useRequest } from 'ahooks';
import { App, ConfigProvider, Form, Input, Modal, Spin,Tree,Switch,Space,Radio} from 'antd';
import type { TreeDataNode, TreeProps } from 'antd';
import Image from 'next/image';
import React, { useCallback, useMemo, useState,useEffect, Children } from 'react';
import { useTranslation } from 'react-i18next';
import styles from '@/pages/construct/app/components/create-app-modal/styles.module.css'

const CreateAuthModal: React.FC<{
  open: boolean;
  onCancel: () => void;
  refresh?: any;
  type?: 'add' | 'edit';
  authInfo: Object
}> = ({ open, onCancel, type = 'add', refresh,authInfo}) => {

  const { t, i18n } = useTranslation();
  const { message } = App.useApp();
  const [appRadios, setAppRadio] = useState('0');
  const [databaseRadios, setDatabaseRadio] = useState('0');
  const [knowledgeRadios, setKnowledgeRadio] = useState('0');
  const [flowRadios, setFlowRadio] = useState('0');

  //层级分组展开
  const [databaseExpandedKeys, setDatabaseExpandedKeys] = useState([]);
  const [knowledgeExpandedKeys, setKnowledgeExpandedKeys] = useState([]);

  const [form] = Form.useForm();
  // const appsAuth = Form.useWatch('app_set', form);  //应用权限开关
  // const databaseAuth = Form.useWatch('connect_set', form); 
  // const knowledgeAuth = Form.useWatch('knowledge_set', form);  
  // const flowAuth = Form.useWatch('flow_set', form); 
  //选中的 授权的值
  const [checkedAppKeys, setAppKeys] = useState([]);
  const [checkedDatabaseKeys, setDatabaseKeys] = useState([]);
  const [checkedKnowledgeKeys, setKnowledgeKeys] = useState([]);
  const [checkedFlowKeys, setFlowKeys] = useState([]);
  // 初始化权限数据
  const [appsTreeData, setAppsTreeData] = useState([]);
  const [databaseTreeData, setDatabaseTree] = useState([]);
  const [knowledgeTreeData, setKnowledgeTree] = useState([]);
  const [flowTreeData, setFlowTree] = useState([]);

  // 动态校验规则
  // const validateAtLeastOneChecked = (_, __, { dependencies }) => {
  //   const values = ['app_set', 'connect_set', 'knowledge_set', 'flow_set'].reduce((acc, field) => {
  //     acc[field] = form.getFieldValue(field);
  //     return acc;
  //   }, {});
    
  //   const hasChecked = Object.values(values).some(Boolean);
  //   return hasChecked ? Promise.resolve() : Promise.reject('至少需要开启一个权限');
  // };

  // 动态必填星号
  // const dynamicRequired = () => {
  //   const values = form.getFieldsValue(['app_set', 'connect_set', 'knowledge_set', 'flow_set']);
  //   return !Object.values(values).some(Boolean);
  // };


  const onCheckApps: TreeProps['onCheck'] = (checkedKeys, info) => {
    setAppKeys(checkedKeys);
  };
  const onCheckDatabase: TreeProps['onCheck'] = (checkedKeys, info) => {
    setDatabaseKeys(checkedKeys);
  };
  const onCheckKnowledge: TreeProps['onCheck'] = (checkedKeys, info) => {
    setKnowledgeKeys(checkedKeys);
  };
  const onCheckFlow: TreeProps['onCheck'] = (checkedKeys, info) => {
    setFlowKeys(checkedKeys);
  };
  // 权限开关
  // const updateSwitch = (value,type)=>{
  //   switch (type) {
  //       case 'apps':
  //           form.setFieldsValue({ app_set: value });
  //         break;
  //       case 'database':
  //         form.setFieldsValue({ connect_set: value });
  //         break;
  //       case 'knowledge':
  //         form.setFieldsValue({ knowledge_set: value });
  //         break;
  //       case 'flow':
  //         form.setFieldsValue({ flow_set: value });
  //         break;
  //       default:
  //   }
  // }

  const toggleAllTrees =  (e,type)=>{
    const value = e.target.value;
    switch (type) {
        case 'app':
          setAppRadio(value)
          const app_allKeys = getAllKeys(appsTreeData,'app_code');
          if(value < 0 ){
            setAppKeys(checkedAppKeys)          
          }else{
            setAppKeys(app_allKeys)
          }
          break;
        case 'database':
          setDatabaseRadio(value)
          const db_allKeys = getAllKeys(databaseTreeData,'id');
          if(value < 0 ){
            setDatabaseExpandedKeys(db_allKeys)
            setDatabaseKeys([])          
          }else{
            setDatabaseExpandedKeys([])
            setDatabaseKeys(db_allKeys)
          }
          break;
        case 'knowledge':
          setKnowledgeRadio(value)
          const allKeys = getAllKeys(knowledgeTreeData,'id');
          if(value < 0 ){
            setKnowledgeExpandedKeys(allKeys)
            setKnowledgeKeys([])
          }else{
            setKnowledgeExpandedKeys([])
            setKnowledgeKeys(allKeys)
          }
          break;
        case 'flow':
          setFlowRadio(value)
          const flow_allKeys = getAllKeys(databaseTreeData,'uid');
          if(value < 0 ){
            setFlowKeys(checkedFlowKeys)          
          }else{
            setFlowKeys(flow_allKeys)
          }
          break;
        default:
    }
  }


  // 创建/编辑 权限
  const { run: createAuth, loading: createLoading } = useRequest(
    async (params) => {
      console.log(params)
      
      if (type === 'edit') {
        return await apiInterceptors(
          updateAuth({
            id: authInfo?.id,
            built_in: authInfo.built_in,
            ...params,
          }),
        );
      } else {      
        return await apiInterceptors(
          addAuth({
            built_in: false,
            ...params,
          }),
        );
      }
    },
    {
      manual: true,
      onSuccess: async res => {     
        const [error, data] = res;
        if (!error) {
          if (type === 'edit') {
            message.success(t('Update_successfully'));
          } else {
            message.success(t('Create_successfully'));
          }
        } else {
          message.error(type === 'edit' ? t('Update_failure') : t('Create_failure'));
        }
        await refresh?.();
        onCancel();
      },
    },
  );

  const getAllKeys = (data,label) => {
    return data.reduce((keys, node) => {
      keys.push(node[label]);
      if (node.children) {
        keys = keys.concat(getAllKeys(node.children,label));
      }
      return keys;
    }, []);
  };

  const initAppsTree = useCallback(async () => {
    const [_, data] = await apiInterceptors(get_app_list());
    setAppsTreeData(data);

    if(type === 'edit'){
      
      if(authInfo.app_set != '-1'){
        if(authInfo.app_set == '0'){
          setAppRadio('0')
          const allKeys = getAllKeys(data,'app_code');
          setAppKeys(allKeys)
        }else{
          setAppRadio('-1')
          const checkedKeys = authInfo.app_set.split(',');
          setAppKeys(checkedKeys)
        }
      }
    }
  },[]);

  const initDatabaseTree = useCallback(async () => {
    const [_, data] = await apiInterceptors(get_connect_group());
    const treeData = []
    for(let it in data){
      treeData.push({
        id:it,
        db_name:it,
        children: data[it]
      })
    }
    
    setDatabaseTree(treeData);

    if(type === 'edit'){
      if(authInfo.connect_set != '-1'){
        const allKeys = getAllKeys(treeData,'id');
        if(authInfo.connect_set == '0'){
          setDatabaseRadio('0')        
          setDatabaseKeys(allKeys)
        }else{
          setDatabaseRadio('-1')
          const checkedKeys = authInfo.connect_set.split(',');
          const newKeys = checkedKeys.map(item =>!isNaN(Number(item))? Number(item) : item);
          setDatabaseKeys(newKeys)
          setDatabaseExpandedKeys(allKeys)
        }
      }
    }
  },[]);

  const initKnowledgeTree = useCallback(async () => {
    const [_, data] = await apiInterceptors(get_knowledge_group());
    const treeData = []
    for(let it in data){
      treeData.push({
        id:it,
        name:it,
        children: data[it]
      })
    }
    
    setKnowledgeTree(treeData);

    if(type === 'edit'){
      
      if(authInfo.knowledge_set != '-1'){
        const allKeys = getAllKeys(treeData,'id');
        if(authInfo.knowledge_set == '0'){
          setKnowledgeRadio('0')      
          setKnowledgeKeys(allKeys)
        }else{
          setKnowledgeRadio('-1')
          const checkedKeys = authInfo.knowledge_set.split(',');
          const newKeys = checkedKeys.map(item =>!isNaN(Number(item))? Number(item) : item);
          setKnowledgeKeys(newKeys)
          setKnowledgeExpandedKeys(allKeys)
        }
      }
    }
  },[]);

  const initFlowTree = useCallback(async () => {
    const [_, data] = await apiInterceptors(get_flow_list());
    setFlowTree(data);

    if(type === 'edit'){
      if(authInfo.flow_set != '-1'){
        if(authInfo.flow_set == '0'){
          setFlowRadio('0')
          const allKeys = getAllKeys(data,'uid');
          setFlowKeys(allKeys)
        }else{
          setFlowRadio('-1')
          const checkedKeys = authInfo.flow_set.split(',');
          setFlowKeys(checkedKeys)
          // setExpandedKeys(checkedKeys)
        }
      }
    }
  },[]);

  
  const setFormdata = useCallback(() => {
    form.setFieldsValue({
      name: authInfo.name,
      desc: authInfo.desc,
      built_in: authInfo.built_in,
      app_set: authInfo.app_set == -1?false:true,   
      connect_set:  authInfo.connect_set == -1?false:true,   
      knowledge_set:authInfo.knowledge_set == -1?false:true,   
      flow_set: authInfo.flow_set == -1?false:true,  
    })
  },[authInfo,form])


  useEffect( () => {
     initAppsTree()
    //  initDatabaseTree()
    //  initKnowledgeTree()
    //  initFlowTree()

    if (type === 'edit') {
       setFormdata();
    }
  },[initAppsTree,setFormdata,type])

  return (
    <ConfigProvider
      theme={{
        components: {
          Button: {
            defaultBorderColor: '#d9d9d9',
          },
        },
      }}
    >
      <Modal
        className={styles['create-app-modal-container']}
        title={type==='add'?t('create') +t('authority'): t('Edit')+t('authority')}
        width={900}
        open={open}
        onOk={async () => {
          form.validateFields().then(async (values: any) => {
            await createAuth({
              name: values?.name,
              desc: values?.desc,
              app_set: values?.app_set ? appRadios < 0  && checkedAppKeys.length ? checkedAppKeys.toString() : '0' : '-1',
              connect_set: '-1',
              knowledge_set: '-1',
              flow_set: '-1',
            });
          });
        }}
        onCancel={onCancel}
        centered={true}
      >
        <Spin spinning={createLoading}>
          <div className='flex flex-1'>
            <Form
              layout='vertical'
              className='w-full'
              form={form}
            >        
              <Form.Item
                label={`${t('auth_name')}：`}
                name='name'
                rules={[{ required: true, message: t('input_auth_text') }]}
              >
                <Input placeholder={t('input_auth_text')} autoComplete='off' className='h-8' disabled={authInfo.built_in} />
              </Form.Item>
              <Form.Item
                label={`${t('Description')}：`}
                name='desc'              
                rules={[
                  {
                    required: true,
                    message: t('Please_input_the_description'),
                  },
                ]}
              >
                <Input.TextArea
                  autoComplete='off'
                  placeholder={t('Please_input_the_description')}
                  autoSize={{ minRows: 2.5 }}
                  disabled={authInfo.built_in}
                />
              </Form.Item>
              {/* 应用权限 */}
              <Form.Item layout="horizontal" 
                name="app_set"
                label={`${t('apps_auth')}：`}
                required
              >
                <Space direction='vertical' className='w-full mt-2 relative bottom-3'>
                    {/* <Switch value={form.getFieldValue('app_set')}
                        onChange={value => {
                            updateSwitch(value, 'apps');
                        }}
                    /> */}
                    
                        <Radio.Group className='w-full border border-[#d6d8da] rounded-sm p-3' 
                            block 
                            options={[
                              { 
                                label: '所有应用(含新增)', 
                                value: '0' 
                              },
                              { label: '全部展开', value: '-1' }
                            ]} 
                            value={appRadios} 
                            onChange={value => {toggleAllTrees(value,'app')}}
                        />

                        {appRadios==-1 && <Tree 
                          fieldNames={{
                            title: 'app_name',
                            key: 'app_code',
                            value:'app_code',
                            children: 'children'
                          }}
                          className='w-full border border-[#d6d8da] p-2 -mt-3' 
                          height={200}
                          checkable
                          defaultExpandAll                        
                          checkedKeys={checkedAppKeys}
                          onCheck={onCheckApps}                
                          treeData={appsTreeData}
                        />}
                   
                </Space>
              </Form.Item>

              {/* 数据库权限 */}
              {/* <Form.Item layout="horizontal" valuePropName="checked"
                name="connect_set"
                label={`${t('database_auth')}：`}
                required={dynamicRequired()}
                rules={[
                  { validator: validateAtLeastOneChecked },
                ]}
                validateFirst
                validateTrigger={['onChange', 'onBlur']}
              >
                <Space direction='vertical' className='w-full mt-2'>
                    <Switch value={form.getFieldValue('connect_set')}
                        onChange={value => {
                            updateSwitch(value, 'database');
                        }}
                    />
                    {databaseAuth && (
                      <>
                          <Radio.Group className='w-full border border-[#d6d8da] rounded-sm p-3 -mb-10' 
                              block 
                              options={[
                                { 
                                  label: '所有数据库(含新增)', 
                                  value: '0' 
                                },
                                { label: '全部展开', value: '-1' }
                              ]} 
                              value={databaseRadios} 
                              onChange={value => 
                              {toggleAllTrees(value,'database')}}
                          />
                         {databaseRadios==-1 &&  <Tree 
                            fieldNames={{
                              title: 'db_name',
                              key: 'id',
                              value:'id',
                              children: 'children'
                            }}
                            className='w-full border border-[#d6d8da]  p-2' 
                            height={200}
                            checkable
                            defaultExpandAll
                            expandedKeys={databaseExpandedKeys}  
                            checkedKeys={checkedDatabaseKeys}
                            onCheck={onCheckDatabase}                
                            treeData={databaseTreeData}
                          />}
                      </>
                    )}
                </Space>
              </Form.Item> */}

              {/* 知识库权限 */}
              {/* <Form.Item layout="horizontal"
                name="knowledge_set"
                label={`${t('knowledge_base_auth')}：`}              
                required={dynamicRequired()}
                rules={[
                  { validator: validateAtLeastOneChecked },
                ]}
                validateFirst
                validateTrigger={['onChange', 'onBlur']}
              >
                <Space direction='vertical' className='w-full'>
                    <Switch value={form.getFieldValue('knowledge_set')}
                        onChange={value => {
                            updateSwitch(value, 'knowledge');
                        }}
                    />
                    {knowledgeAuth && (
                      <>
                        <Radio.Group className='w-full border border-[#d6d8da] rounded-sm p-3 -mb-10' 
                            block 
                            options={[
                              { 
                                label: '所有知识库(含新增)', 
                                value: '0' 
                              },
                              { label: '全部展开', value: '-1' }
                            ]} 
                            value={knowledgeRadios} 
                            onChange={value => {toggleAllTrees(value,'knowledge')}}
                        />
                        { knowledgeRadios ==-1 && <Tree 
                          fieldNames={{
                            title: 'name',
                            key: 'id',
                            value:'id',
                            children: 'children'
                          }}
                          className='w-full border border-[#d6d8da] p-2' 
                          height={200}
                          checkable                      
                          defaultExpandAll    
                          expandedKeys={knowledgeExpandedKeys}        
                          checkedKeys={checkedKnowledgeKeys}
                          onCheck={onCheckKnowledge}                
                          treeData={knowledgeTreeData}
                        />}
                      </>
                    )}
                </Space>
              </Form.Item> */}

              {/* 工作流权限 */}
              {/* <Form.Item layout="horizontal"
                name="flow_set"
                label={`${t('flow_auth')}：`}
                required={dynamicRequired()}
                rules={[
                  { validator: validateAtLeastOneChecked },
                ]}
                validateFirst
                validateTrigger={['onChange', 'onBlur']}
              >
                <Space direction='vertical' className='w-full mt-2'>
                    <Switch value={form.getFieldValue('flow_set')}
                        onChange={value => {
                            updateSwitch(value, 'flow');
                        }}
                    />
                    {flowAuth && (
                      <>
                          <Radio.Group className='w-full border border-[#d6d8da] rounded-sm p-3 -mb-10' 
                              block 
                              options={[
                                { 
                                  label: '所有工作流(含新增)', 
                                  value: '0' 
                                },
                                { label: '全部展开', value: '-1' }
                              ]} 
                              value={flowRadios} 
                              onChange={value => {toggleAllTrees(value,'flow')}}
                          />
                         { flowRadios ==-1 && <Tree 
                            fieldNames={{
                              title: 'name',
                              key: 'uid',
                              value:'uid',
                              children: 'children'
                            }}
                            className='w-full border border-[#d6d8da] p-2' 
                            height={200}
                            checkable
                            defaultExpandAll                          
                            checkedKeys={checkedFlowKeys}
                            onCheck={onCheckFlow}                
                            treeData={flowTreeData}
                          />}
                      </>
                    )}
                </Space>
              </Form.Item> */}
            </Form>
          </div>
        </Spin>
      </Modal>
    </ConfigProvider>
  );
};

export default CreateAuthModal;
